<?php

/**
 * 订单列表
 * @author renjianhong
 * @date 2021-8-04 14:35
 */
namespace Modules\Order\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Order\Http\Controllers\Controller;
use Modules\Order\Entities\OrderRefund;
use Modules\Order\Entities\Order;
use Modules\Order\Entities\OrderDetail;
use Modules\Order\Entities\Goods;
use Modules\Order\Entities\RefundAddress;
use Modules\Order\Entities\User;
use Modules\Order\Repositories\Admin\RefundInterface;
use Modules\Order\Services\Common\RefundServices;


class OrderRefundController extends Controller
{
    private $refundInterface;
    
    public function __construct(RefundInterface $refundInterface)
    {
        $this->refundInterface = $refundInterface;
        
    }

    /**
     * 售后订单列表
     * @param OrderRefund $OrderRefundModel
     * @param RefundAddress $RefundAddressModel
     * @return bool|\Illuminate\Auth\Access\Response|\Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function list(OrderRefund $OrderRefundModel, RefundAddress $RefundAddressModel)
    {
        try {
            $address_list = $RefundAddressModel->where('is_delete',0)->orderByDesc('id')->get();
        } catch (\Exception $e) {
            $address_list = [];
        }

        return view('order::admin.order_refund.list',compact('OrderRefundModel','address_list'));
    }

    /**
     * ajax获取列表数据
     */
    public function ajaxList(Request $request, OrderRefund $OrderRefundModel)
    {
        $pagesize = $request->input('limit'); // 每页条数
        $page = $request->input('page',1);//当前页
        $order_no = $request->input('order_no');
        $nickname = $request->input('nickname');
        $name = $request->input('name');
        $mobile = $request->input('mobile');
        $begin_time = $request->input('begin_time');//开始时间
        $end_time = $request->input('end_time');//结束时间
        $refund_status = $request->input('refund_status');//售后订单状态

        $where = [
            ['order.order_no', 'like', '%'.$order_no.'%'],
            ['order.name', 'like', '%'.$name.'%'],
            ['users.nickname', 'like', '%'.$nickname.'%'],
            ['order_refund.is_delete', '=', '0'],
        ];
        if($mobile){
            $where[] = ['order.mobile', '=', $mobile];
        }
        if($begin_time){
            $where[] = ['order_refund.created_at', '>=', $begin_time];
        }
        if($end_time){
            $where[] = ['order_refund.created_at', '<=', $end_time];
        }
        if($refund_status != ''){
            $where[] = ['order_refund.refund_status', '=', $refund_status];
        }
        //获取总条数
        $count = $OrderRefundModel
                ->leftJoin('order', 'order.id', '=', 'order_refund.order_id')   
                ->leftJoin('users', 'users.id', '=', 'order_refund.user_id')
                ->where($where)
                ->count();
        
        //求偏移量
        $offset = ($page-1)*$pagesize;
        $list = $OrderRefundModel
                ->leftJoin('order', 'order.id', '=', 'order_refund.order_id')   
                ->leftJoin('users', 'users.id', '=', 'order_refund.user_id')   
                ->where($where)
                ->select('order_refund.*','order.order_no','order.name','order.mobile','order.address','users.nickname','users.avatar')
                ->orderByDesc('id')->offset($offset)->limit($pagesize)->get();
        foreach($list as $key => $v){
            $order_detail = OrderDetail::where('order_id',$v['order_detail_id'])->get();//订单商品详情
            foreach($order_detail as $index => &$dl){
                $order_detail[$index]['goods_attr'] = json_decode($dl['goods_attr'],true);
                $is_domain = $OrderRefundModel->getIsDomain($dl['goods_pic']);
                if($is_domain){
                    $order_detail[$index]['goods_pic'] = $dl['goods_pic'];
                }else{
                    $order_detail[$index]['goods_pic'] = $OrderRefundModel->getShowImage($dl['goods_pic']);
                }
            }
            $list[$key]['order_detail'] = $order_detail;
            $is_domain = $OrderRefundModel->getIsDomain($v['avatar']);
            if($is_domain){
                $list[$key]['avatar'] = $v['avatar'];
            }else{
                $list[$key]['avatar'] = $OrderRefundModel->getShowImage($v['avatar']);
            }
            $list[$key]['refund_status_name'] = $OrderRefundModel->getRefundStatus($v);
            $list[$key]['refund_type_name'] = $OrderRefundModel->getRefundType($v['refund_type']);
            $list[$key]['refund_address'] = RefundAddress::where('id',$v['refund_address_id'])->value('address');
        }
        
        return $this->success(compact('list', 'count'));
    }

    /**
     * 处理售后订单
     */
    public function refundHandle(Request $request, OrderRefund $OrderRefundModel)
    {
        if($request->isMethod('post')){
            $data = $request->input();
            
            $id = $data['id'];
            $order_refund = $OrderRefundModel->where('id',$id)->first();
            if(!$order_refund){
                return $this->failed('售后订单不存在');
            }
            if($order_refund->refund_status != 0){
                return $this->failed('该订单已处理');
            }
            if($order_refund->refund_type == 1){
                //仅退款
//                return $this->refundOnly($order_refund, $data);

                //退款退货
                return $this->refundReturn($order_refund, $data);
            }elseif($order_refund->refund_type == 2){
                //退款退货
//                return $this->refundReturn($order_refund, $data);

                //换货处理
                return $this->exchangeOnly($order_refund, $data);
            }elseif($order_refund->refund_type == 3){
                //换货处理
                return $this->exchangeOnly($order_refund, $data);
            }
            
        }
        
    }

    /**
     * 退款处理
     */
    public function refundOnly($order_refund, $data)
    {
        try{
            if($data['action'] == 1){
                //同意
                if($data['refund_price'] > $order_refund->refund_price){
                    return $this->failed('退款金额不能大于'.$order_refund->refund_price);
                }
                if(!$data['refund_pay_type']){
                    return $this->failed('请选择退款方式');
                }
                if($data['refund_pay_type'] == 1){
                    $reulst = $this->refundInterface->refundReturn($data,$order_refund);
                }elseif($data['refund_pay_type'] == 2){
                    $reulst = $this->refundInterface->refundBalance($data,$order_refund);//退回余额
                }elseif($data['refund_pay_type'] == 3){
                    $reulst = $this->refundInterface->refundOffline($data,$order_refund);//线下转账
                }
                return $this->success($reulst);
            }
            if($data['action'] == 2){
                //拒绝
                $order_refund->refund_status = 3;
                $order_refund->refuse_desc = $data['refuse_desc'];
                $order_refund->response_time = date('Y-m-d H:i:s');
                if ($order_refund->save()) {
                    return $this->success('操作成功');
                }else{
                    return $this->failed('操作失败');
                }
            }
        } catch(\Exception $e){
            return $this->failed($e->getMessage());
        }
       
    }

    /**
     * 退货处理
     * @param $order_refund
     * @param $data
     * @return mixed
     * @author tan bing
     * @date 2021-11-18 10:13
     */
    public function refundReturn($order_refund, $data)
    {
        if($data['action'] == 1){
            //同意
            if ($data['refund'] != 1) {
                //仅同意，还未退款
                if ($data['refund_price']) {
                    if ($data['refund_price'] > $order_refund->refund_price) {
                        return $this->failed('退款金额不能大于'.$order_refund->refund_price);
                    }
                    $order_refund->refund_price = $data['refund_price'];
                }
                if(!$data['refund_address_id']){
                    return $this->failed('退货地址不能为空');
                };
                $order_refund->refund_address_id = $data['refund_address_id'];
                $order_refund->is_agree = 1;
                $order_refund->save();

                return $this->success('已同意退货');
            }else{
                if(!$data['refund_pay_type']){
                    return $this->failed('请选择退款方式');
                }
                try {
                    $order = Order::where('id',$order_refund->order_id)->first();
                    if($order->order_status == 8) {
                        return $this->failed('该订单已退款，无需重复退款');
                    }
                    $payType = $order->pay_type;
                    $refundServices = new RefundServices();
                    if($data['refund_pay_type'] == 1){
                        $res = $refundServices->refundHandle($order, $order->order_no, $data['refund_price'], $payType);//原路返回
//                        $reulst = $this->refundInterface->refundReturn($data,$order_refund);

                    }elseif($data['refund_pay_type'] == 2){
                        $res = $refundServices->balanceRefund($order, $data['refund_price']);//退回余额
//                        $reulst = $this->refundInterface->refundBalance($data,$order_refund);

                    }elseif($data['refund_pay_type'] == 3){
                        $res = $this->refundInterface->refundOffline($data,$order_refund);//线下转账
                    }

                    $order_refund->refund_status = 1;
                    $order_refund->refund_price = $data['refund_price'];
                    $order_refund->response_time = date('Y-m-d H:i:s');
                    $order_refund->refund_pay_type = $data['refund_pay_type'];
                    $order_refund->save();

                    $order->order_status = 8;
                    $order->save();
                } catch (\Exception $e) {
                    return $this->failed($e->getMessage());
                }

                return $this->success($res);
            }
        }
        if($data['action'] == 2){
            //拒绝
            $order_refund->refund_status = 3;
            $order_refund->refuse_desc = $data['refuse_desc'];
            $order_refund->response_time = date('Y-m-d H:i:s');
            if ($order_refund->save()) {
                return $this->success('操作成功');
            }else{
                return $this->failed('操作失败');
            }
        }
    }

    /**
     * 换货处理
     */
    public function exchangeOnly($order_refund, $data)
    {
        if($data['action'] == 1){
            //同意
            $order_refund->refund_status = 2;
            $order_refund->is_agree = 1;
            if(!$data['refund_address_id']){
                return $this->failed('退货地址不能为空');
            }
            $order_refund->refund_address_id = $data['refund_address_id'];
            $order_refund->response_time = date('Y-m-d H:i:s');
            if ($order_refund->save()) {
                $order = Order::where('id',$order_refund->order_id)->first();
                $order->order_status = 8;
                $order->save();
                return $this->success('操作成功');
            }else{
                return $this->failed('操作失败');
            }
        }
        if($data['action'] == 2){
            //拒绝
            $order_refund->refund_status = 3;
            $order_refund->refuse_desc = $data['refuse_desc'];
            $order_refund->response_time = date('Y-m-d H:i:s');
            if ($order_refund->save()) {
                return $this->success('操作成功');
            }else{
                return $this->failed('操作失败');
            }
        }
    }

    /**
     * 删除订单
     */
    public function delete(Request $request, OrderRefund $OrderRefundModel){
        if($request->isMethod('post')){
            $id = $request->input('id');
            if($id){
                $reulst = $OrderRefundModel->where('id',$id)->update(['is_delete'=>1]);
                if($reulst){
                    return $this->success('操作成功');
                }else{
                    return $this->failed('操作失败');
                }
            }else{
                return $this->failed('缺少参数id');
            }
        }
    }

    /**
     * 售后订单详情
     */
    public function detail(Request $request, OrderRefund $OrderRefundModel)
    {   
        
        $id = $request->input('id');
        $info = $OrderRefundModel->leftJoin('users', 'users.id', '=', 'order_refund.user_id')
                ->leftJoin('order', 'order.id', '=', 'order_refund.order_id')      
                ->where('order_refund.id',$id)
                ->select('order_refund.*','users.nickname','users.avatar','order.total_price','order.pay_price','order.express_price')
                ->first();
                
        $info->refund_type = $OrderRefundModel->getRefundType($info->refund_type);
        $info->refund_status = $OrderRefundModel->getRefundStatus($info);
        $info->refund_pay_type = $OrderRefundModel->refundPayType($info->refund_pay_type);
        $info->pic_list = json_decode($info->pic_list,true);
        $order_detail = OrderDetail::where('order_id',$info['order_id'])->get();//订单商品详情
        foreach($order_detail as $index => &$dl){
            $order_detail[$index]['goods_attr'] = json_decode($dl['goods_attr'],true);
        }
        return view('order::admin.order_refund.detail',compact('info','order_detail'));
        
    }

}
